package com.alstudio.net.protocol.xmpp.parser.iq;

import java.io.IOException;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParserException;

import com.alstudio.net.protocol.xmpp.XmppListener;
import com.alstudio.net.protocol.xmpp.packact.IQ;
import com.alstudio.net.protocol.xmpp.packact.IQType;
import com.alstudio.net.protocol.xmpp.parser.BaseParser;
import com.alstudio.net.protocol.xmpp.parser.iq.IQParseEventHandler.IQXmlParseEventCallback;
import com.alstudio.utils.log.Mylog;
import com.alstudio.utils.xml.BaseXmlParser;

public abstract class BaseIQParser extends BaseParser implements IQPackageCallback {

	private final String TAG = "IQParser";
	protected XmppListener mListener;
	protected BaseIqXmlParser mParser;
	protected IQType mIqType = IQType.RESULT;
	protected final String ERROR_CODE_TAG = "error";


	@Override
	public void parseIQPackage(IQ packact, String stream, XmppListener listener)
			throws Exception {
	}

	protected void startParse(IQ packact, String stream,
			IQXmlParseEventCallback listener) {
		try {
			mParser = new BaseIqXmlParser(stream, packact.getType(), listener);
			mParser.start();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Mylog.e(e.toString());
		}finally{
			packact = null;
			stream = null;
		}
	}

	/**
	 * 读取节点内容
	 * 
	 * @return
	 * @throws XmlPullParserException
	 * @throws IOException
	 */
	protected String readText(){
		try {
			return mParser.readText();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} 
	}

	/**
	 * 获取节点所有属性
	 * 
	 * @param tag
	 * @return
	 * @throws XmlPullParserException
	 * @throws IOException
	 */
	protected ArrayList<String> getAttributes(final String tag)
			throws XmlPullParserException, IOException {
		return mParser.getAttributes(tag);
	}

	/**
	 * 获取属性内容
	 * 
	 * @param att
	 * @return
	 */
	protected String getAttValue(String att) {
		return mParser.getAttValue(att);
	}
	
	protected class BaseIqXmlParser extends BaseXmlParser {

		private IQXmlParseEventCallback mCallback;
		protected IQType mType;

		protected BaseIqXmlParser(String xml, IQType type,
				IQXmlParseEventCallback callback) throws XmlPullParserException {
			// TODO Auto-generated constructor stub
			mType = type;
			mCallback = callback;
			createParser(xml);
		}

		protected void setCallback(IQXmlParseEventCallback callback) {
			mCallback = callback;
		}

		protected void start() throws XmlPullParserException, IOException {
			IQParseEventHandler handler = new IQParseEventHandler(this, mType,
					mCallback);
			setXmlParseCallback(handler);
			handler.startParse();
		}
	}

	public abstract void onCallback();

	
}
